<template>
  <!-- 面包屑导航区域 -->
  <breadcrumb :childMenu="['商品管理', '商品参数']"></breadcrumb>
  <!-- 卡片视图区域 -->
  <el-card>
    <el-alert
      title="注意:只允许为第三级分类设置相关参数！"
      type="warning"
      closable="false"
      show-icon
    ></el-alert>
    <!-- 选择商品分类区域 -->
    <el-row class="cat_opt">
      <el-col>
        <span> 选择商品分类： </span>
        <el-cascader
          v-model="selectedKeys"
          :options="cateKeyNames"
          :props="{
            expandTrigger: 'hover',
            value: 'id',
            label: 'cateName',
            children: 'children'
          }"
          @change="selectChanged"
        >
        </el-cascader>
      </el-col>
    </el-row>
    <el-row>
      <el-col>
        <el-tabs v-model="activeName" @tab-click="handleTabClick">
          <!-- 添加动态参数的面板 -->
          <el-tab-pane label="动态参数" name="many">
            <el-button
              type="primary"
              size="mini"
              :disabled="selectedKeys.length !== 3"
              @click="addDialogVisible = true"
              >添加参数</el-button
            >
            <!-- 动态参数表格 -->
            <el-table :data="manyTableData" border stripe>
              <!-- 展开行 -->
              <el-table-column type="expand">
                <template v-slot="props">
                  <!-- 循环渲染tag标签 -->
                  <el-tag
                    v-for="(item, i) in props.row.paramValues"
                    :key="i"
                    closable
                    @close="handleClose(i, props.row)"
                    >{{ item }}</el-tag
                  >
                  <el-input
                    v-if="props.row.inputVisible"
                    ref="saveTagInput"
                    v-model="props.row.inputValue"
                    class="input-new-tag"
                    size="mini"
                    @keyup.enter="handleInputConfirm(props.row)"
                    @blur="handleInputConfirm(props.row)"
                  >
                  </el-input>
                  <el-button
                    v-else
                    class="button-new-tag"
                    size="small"
                    @click="showInput(props.row)"
                    >+ New Tag</el-button
                  >
                </template>
              </el-table-column>
              <!-- 索引列 -->
              <el-table-column type="index" label="#"></el-table-column>
              <el-table-column
                prop="paramName"
                label="参数名称"
              ></el-table-column>
              <el-table-column label="操作">
                <template v-slot="props">
                  <el-button
                    type="primary"
                    icon="el-icon-edit"
                    size="mini"
                    @click="showEditDiag(props.row.id)"
                    >编辑</el-button
                  >
                  <el-button
                    type="danger"
                    icon="el-icon-delete"
                    size="mini"
                    @click="deleteParam(props.row.id)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <!-- 添加静态属性的面板 -->
          <el-tab-pane label="静态属性" name="only">
            <el-button
              type="primary"
              size="mini"
              :disabled="selectedKeys.length !== 3"
              @click="addDialogVisible = true"
              >添加属性</el-button
            >
            <!-- 静态属性表格 -->
            <el-table :data="onlyTableData" border stripe>
              <!-- 展开行 -->
              <el-table-column type="expand">
                <template v-slot="props">
                  <!-- 循环渲染tag标签 -->
                  <el-tag
                    v-for="(item, i) in props.row.paramValues"
                    :key="i"
                    closable
                    @close="handleClose(i, props.row)"
                    >{{ item }}</el-tag
                  >
                  <el-input
                    v-if="props.row.inputVisible"
                    ref="saveTagInput"
                    v-model="props.row.inputValue"
                    class="input-new-tag"
                    size="mini"
                    @keyup.enter="handleInputConfirm(props.row)"
                    @blur="handleInputConfirm(props.row)"
                  >
                  </el-input>
                  <el-button
                    v-else
                    class="button-new-tag"
                    size="small"
                    @click="showInput(props.row)"
                    >+ New Tag</el-button
                  >
                </template>
              </el-table-column>
              <!-- 索引列 -->
              <el-table-column type="index" label="#"></el-table-column>
              <el-table-column
                prop="paramName"
                label="参数名称"
              ></el-table-column>
              <el-table-column label="操作">
                <template v-slot="props">
                  <el-button
                    type="primary"
                    icon="el-icon-edit"
                    size="mini"
                    @click="showEditDiag(props.row.id)"
                    >编辑</el-button
                  >
                  <el-button
                    type="danger"
                    icon="el-icon-delete"
                    size="mini"
                    @click="deleteParam(props.row.id)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </el-col>
    </el-row>
  </el-card>
  <!-- 添加参数的对话框 -->
  <el-dialog
    :title="activeName === 'only' ? '添加静态属性' : '添加动态参数'"
    v-model="addDialogVisible"
    width="50%"
    @close="addDialogClose"
  >
    <!-- 内容主体区域 -->
    <!-- 表单中model和rules名称不可以相同 -->
    <el-form
      ref="addFormRef"
      :model="addForm"
      :rules="addFormRules"
      label-width="80px"
    >
      <el-form-item
        :label="activeName === 'only' ? '静态属性' : '动态参数'"
        prop="paramName"
      >
        <el-input v-model="addForm.paramName"></el-input>
      </el-form-item>
    </el-form>
    <!-- 底部区域 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="addDialogClose">取 消</el-button>
        <el-button type="primary" @click="addCateParam">确 定</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 修改参数的对话框 -->
  <el-dialog
    :title="activeName === 'only' ? '修改静态属性' : '添加动态参数'"
    v-model="editDialogVisible"
    width="50%"
    @close="editDialogClose"
  >
    <!-- 内容主体区域 -->
    <!-- 表单中model和rules名称不可以相同 -->
    <el-form
      ref="editFormRef"
      :model="editForm"
      :rules="editFormRules"
      label-width="80px"
    >
      <el-form-item
        :label="activeName === 'only' ? '静态属性' : '动态参数'"
        prop="paramName"
      >
        <el-input v-model="editForm.paramName"></el-input>
      </el-form-item>
    </el-form>
    <!-- 底部区域 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="editDialogClose">取 消</el-button>
        <el-button type="primary" @click="editCateParam">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import Breadcrumb from "@/common/Breadcrumb.vue";
import {
  getCategoryKeyName,
  getCategoryAttributes,
  addCategoryParam,
  editCategoryParam,
  getCategoryParam,
  deleteCateParam
} from "network/category.js";
export default {
  components: {
    Breadcrumb
  },
  data() {
    return {
      //级联选择器绑定的数据源
      cateKeyNames: [],
      //级联选择器选中的数据
      selectedKeys: [],
      activeName: "many",
      // 动态参数数据
      manyTableData: [],
      // 静态属性数据
      onlyTableData: [],
      //显示/隐藏 添加动态参数/静态属性的对话框
      addDialogVisible: false,
      //添加参数/属性的表单的数据对象
      addForm: {
        paramName: "",
        paramSelType: "",
        paramValues: "",
        cateId: ""
      },
      //添加表单的验证规则对象
      addFormRules: {
        paramName: [
          { required: true, message: "请输入参数名称", trigger: "blur" }
        ]
      },
      //显示/隐藏 修改动态参数/静态属性的对话框
      editDialogVisible: false,
      //修改参数/属性的表单的数据对象
      editForm: {
        id: "",
        paramName: "",
        paramSelType: "",
        paramValues: "",
        paramWriteType: ""
      },
      stest: {},
      //修改表单的验证规则对象
      editFormRules: {
        paramName: [
          { required: true, message: "请输入参数名称", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getCategoryKeyName();
  },

  methods: {
    //查询商品分类id和名称
    async getCategoryKeyName() {
      const res = await getCategoryKeyName("3");
      if (res.status !== 200)
        return this.$message.error({ showClose: true, message: res.msg });
      this.cateKeyNames = res.response;
    },
    //级联选择器选中数据发生变化
    selectChanged() {
      this.getCateParams();
    },
    handleTabClick() {
      this.getCateParams();
    },

    async getCateParams() {
      //证明选中的不是三级分类
      if (this.selectedKeys && this.selectedKeys.length !== 3) {
        this.selectedKeys = [];
        this.manyTableData = [];
        this.onlyTableData = [];
        return;
      }
      //根据所选分类的id,和当前所处的面板,获取对应的参数
      const res = await getCategoryAttributes(
        this.selectedKeys[2],
        this.activeName
      );
      if (!res.success) {
        return this.$message.err({ showClose: true, message: res.msg });
        this.manyTableData = [];
        this.onlyTableData = [];
      }
      res.response.forEach(item => {
        item.paramValues = item.paramValues ? item.paramValues.split(",") : [];
        //控制el-tag输入文本框的显示与隐藏
        item.inputVisible = false;
        // 文本框中输入的内容
        item.inputValue = "";
      });
      if (this.activeName == "only") this.onlyTableData = res.response;
      else this.manyTableData = res.response;
    },

    //关闭添加动态参数/静态属性的对话框
    addDialogClose() {
      this.addDialogVisible = false;
      this.$refs.addFormRef.resetFields();
    },
    //关闭修改动态参数/静态属性的对话框
    editDialogClose() {
      this.editDialogVisible = false;
      this.$refs.editFormRef.resetFields();
    },
    //添加动态参数/静态属性
    addCateParam() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return;
        this.addForm.paramSelType = this.activeName;
        this.addForm.cateId = this.selectedKeys[2];
        const res = await addCategoryParam(this.selectedKeys[2], this.addForm);
        if (!res.success)
          return this.$message.error({ showClose: true, message: res.msg });
        this.getCateParams();
        this.addDialogClose();
      });
    },
    //展示编辑动态参数/静态属性的对话框
    async showEditDiag(id) {
      const res = await getCategoryParam(this.selectedKeys[2], id);
      if (!res.success)
        return this.$message.error({ showClose: true, message: res.msg });
      this.editForm = res.response;
      this.editDialogVisible = true;
    },
    //编辑对话框
    editCateParam() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return;
        const res = await editCategoryParam(this.editForm);
        if (!res.success)
          return this.$message.error({ showClose: true, message: res.msg });
        this.getCateParams();
        this.editDialogClose();
      });
    },
    //根据id删除商品分类的动态参数/静态属性
    async deleteParam(id) {
      const confirmResult = await this.$confirm(
        "此操作将永久删除该参数,是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      if (confirmResult !== "confirm") return this.$message.info("已取消操作");
      //删除
      const res = await deleteCateParam(this.selectedKeys[2], id);
      if (!res.success)
        return this.$message.error({ showClose: true, message: res.msg });
      this.$message.success({ showClose: true, message: "删除成功" });
      this.getCateParams();
    },
    //文本框失去焦点,或按下了enter都会触发
    handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = "";
        row.inputVisible = false;
        return;
      }
      //如果没有return,则证明输入的内容,需要做后续的处理
      row.paramValues.push(row.inputValue.trim());
      row.inputValue = "";
      row.inputVisible = false;
      this.updateParamValues(row);
    },
    //点击按钮展示文本输入框
    showInput(row) {
      row.inputVisible = true;

      //$nextTick作用,就是当页面上的元素被重新渲染之后,才会指定回调函数中的代码
      // this.$nextTick(() => {
      //   this.$refs.saveTagInput.$refs.input.focus();
      // });
    },
    //更新参数属性中的paramValue
    async updateParamValues(row) {
      const param = await getCategoryParam(this.selectedKeys[2], row.id);
      if (!param.success)
        return this.$message.error({ showClose: true, message: param.msg });
      this.editForm = param.response;
      this.editForm.paramValues = row.paramValues.join(",");
      const res = await editCategoryParam(this.editForm);
      if (!res.success)
        return this.$message.error({ showClose: true, message: res.msg });
      return this.$message.success({ showClose: true, message: res.msg });
    },

    handleClose(i, row) {
      row.paramValues.splice(i, 1);
      this.updateParamValues(row);
    }
  }
};
</script>

<style lang="less" scoped>
.cat_opt {
  margin: 15px 0;
}

.el-tag {
  margin: 5px;
}
.input-new-tag {
  width: 100px;
}
</style>
